package lc.com.lcpicturebackend.manager.app.adviser;


import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.advisor.api.*;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.MessageAggregator;
import reactor.core.publisher.Flux;

/**
 * 自定义日志拦截
 */
@Slf4j
public class MyLoggerAdvisor implements CallAroundAdvisor, StreamAroundAdvisor {

	@Override
	public String getName() {
		return this.getClass().getSimpleName();
	}

	@Override
	public int getOrder() {
		return 0;
	}

	private AdvisedRequest before(AdvisedRequest request) {
		log.info("request: {}", request);
		String userid =(String)request.adviseContext().get("userid");
		log.info("userid: {}", userid);
		return request;
	}

	private void observeAfter(AdvisedResponse advisedResponse) {
		log.info("response: {}",advisedResponse);
	}

	@Override
	public String toString() {
		return MyLoggerAdvisor.class.getSimpleName();
	}

	@Override
	public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) {
		// 1.处理请求（前置处理）
		advisedRequest = before(advisedRequest);
		// 2.调用下一个拦截器
		AdvisedResponse advisedResponse = chain.nextAroundCall(advisedRequest);
		// 3.处理响应（后置处理）
		observeAfter(advisedResponse);

		return advisedResponse;
	}

	@Override
	public Flux<AdvisedResponse> aroundStream(AdvisedRequest advisedRequest, StreamAroundAdvisorChain chain) {

		advisedRequest = before(advisedRequest);

		Flux<AdvisedResponse> advisedResponses = chain.nextAroundStream(advisedRequest);
		// 通过MessageAggregator工具类将Flux响应聚合成单个AdvisedResponse
		return new MessageAggregator().aggregateAdvisedResponse(advisedResponses, this::observeAfter);
	}

}
